/**
 * <p>
 * 实现功能：单据通用
 * <p/>
 *
 * @author 秦有宝
 * @version 1.0.00
 */
EUI.Common = {
    lang:{},
    dateCompare:function(startTime, endTime) {
        var g = this;
        var start = new Date(startTime.replace("-", "/").replace("-", "/"));
        var end = new Date(endTime.replace("-", "/").replace("-", "/"));
        if (start && end && start.getTime() > end.getTime()) {
            //timeCompareText:"起始时间必须小于截止时间！",
            EUI.Common.message(g.lang.timeCompareText);
            return false;
        }
        return true;
    },
    createOrder:function() {
        var html = '<div class="order">'+
            '<div class="menu">'+
            '<ul>'+
            '<li class="baseinfo" style="background: #40add5;margin-right: 1px;"><a href="#">档案信息</a></li>'+
            '<div class="wrapper" id="documentcategorywrapper">'+
            '<div class="scroller">'+
            '<ul class="clearfix">'+
            '</ul>'+
            '</div>'+
            '</div>'+
            '<li class="drop-down all" style="float:right;background: #40add5;height: 44px;"><div class="ecmp-common-more"></div>'+
            '<div class="mega-menu">'+
            '<div class="mega-menu-column">'+
            '<p>所有文档分类</p>'+
            ' <span class="categories-list">'+
            '</span>'+
            '</div>'+
            '</div>'+
            '</li>'+
            '</ul>'+
            '</div>'+
            '<div class="doccontent">'+
            '<div id="content-baseinfo" style="display: none"></div>'+
            '</div>'+
            '</div>';
        return $(html);
    },
    createMainHtml:function() {
        var html = '<div class="order">'+
            '<div class="menu">'+
            '<ul>'+
            '<div class="wrapper" style="width: 1072px;" id="documentcategorywrapper">'+
            '<div class="scroller">'+
            '<ul class="clearfix">'+
            '</ul>'+
            '</div>'+
            '</div>'+
            '<li class="drop-down all" style="float:right;background: #40add5;height: 44px;"><div class="ecmp-common-more"></div>'+
            '<div class="mega-menu">'+
            '<div class="mega-menu-column">'+
            '<p>所有文档分类</p>'+
            ' <span class="categories-list">'+
            '</span>'+
            '</div>'+
            '</div>'+
            '</li>'+
            '</ul>'+
            '</div>'+
            '<div class="doccontent">'+
            '<div id="content-baseinfo" style="display: none"></div>'+
            '</div>'+
            '</div>';
        return $(html);
    },
    ieVersion:function () {
        var userAgent = navigator.userAgent;    //取得浏览器的userAgent字符串
        var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
        var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
        var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
        if(isIE) {
            var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
            reIE.test(userAgent);
            var fIEVersion = parseFloat(RegExp["$1"]);
            if(fIEVersion == 7) {
                return 7;
            } else if(fIEVersion == 8) {
                return 8;
            } else if(fIEVersion == 9) {
                return 9;
            } else if(fIEVersion == 10) {
                return 10;
            } else {
                return 6;//IE版本<=7
            }
        } else if(isEdge) {
            return 'edge';//edge
        } else if(isIE11) {
            return 11; //IE11
        }else{
            return -1;//不是ie浏览器
        }
    },
    /*   createOrder:function(mainTitle, accountingState) {
     var html = '<div id="orderBox" class="orderBox">'+
     '<div id="orderBoxHead" class="orderBoxHead">'+
     '<div class="title_bg">'+
     '<div class="maintitle">'+mainTitle+'</div>'+
     '</div>'+
     '<div class="div-barcode">'+
     '<img id="imgBarCode" />'+
     '</div>'+
     '</div>'+
     '<div id="requestextinfo"></div>'+
     '<div id="requesthead"></div>'+
     '<div id="categorytitle">'+
     '<div id="doccatetitle">文档分类</div>'+
     '<div class="wrapper" id="documentcategorywrapper">'+
     '<div class="scroller">'+
     '<ul class="clearfix">'+
     '</ul>'+
     '</div>'+
     '</div>'+
     '</div>'+
     // '<div id="attachmentBox"></div>'+
     //attachmentBox
     '</div>';
     return $(html);
     },*/
    dateFormat:function(time) {
        if (time) {
            var date = new Date(time);
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            return date.getFullYear() + "-" + month + "-" + currentDate;
        }
        return "";
    },
    /* 获取上一个月
     *
     * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
     * @return "2013-12-25"
     */
    getPreMonth:function(date) {
        var arr = date.split('-');
        var year = arr[0];
        var month = arr[1];
        var day = arr[2];
        var days = new Date(year, month, 0);
        days = days.getDate();
        var year2 = year;
        var month2 = parseInt(month) - 1;
        if (month2 == 0) {
            year2 = parseInt(year2) - 1;
            month2 = 12;
        }
        var day2 = day;
        var days2 = new Date(year2, month2, 0);
        days2 = days2.getDate();
        if (day2 > days2) {
            day2 = days2;
        }
        if (month2 < 10) {
            month2 = '0' + month2;
        }
        var t2 = year2 + '-' + month2 + '-' + day2;
        return t2;
    } ,

    dateCompare2:function(startTime, endTime) {
        var g = this;
        var start = new Date(startTime.replace("-", "/").replace("-", "/"));
        var end = new Date(endTime.replace("-", "/").replace("-", "/"));
        if (start && end && start.getTime() > end.getTime()) {
            return false;
        }
        return true;
    },
    uuid: {
        set:function() {
            var value;
            if (this.isValid(arguments[0])) {
                value = arguments[0];
            } else {
                value = this.empty();
            }
            $(this).data("value", value);
            return value;
        },
        empty:function() {
            return "00000000-0000-0000-0000-000000000000";
        },
        isEmpty:function(uid) {
            return uid == EUI.Common.uuid.empty() || typeof (uid) == 'undefined' || uid == null || uid == '';
        },
        isValid:function(value) {
            var rGx = new RegExp("\\b(?:[A-F0-9]{8})(?:-[A-F0-9]{4}){3}-(?:[A-F0-9]{12})\\b");
            return rGx.exec(value) != null;
        },
        newUuid:function() {
            var value;
            if (arguments.length == 1 && this.isValid(arguments[0])) {
                $(this).data("value", arguments[0]);
                value = arguments[0];
                return value;
            }
            var res = [], hv;
            var rgx = new RegExp("[2345]");
            for (var i = 0; i < 8; i++) {
                hv = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                if (rgx.exec(i.toString()) != null) {
                    if (i == 3) { hv = "6" + hv.substr(1, 3); }
                    res.push("-");
                }
                res.push(hv.toUpperCase());
            }
            value = res.join('');
            $(this).data("value", value);
            return value;
        },
        value:function() {
            if ($(this).data("value")) {
                return $(this).data("value");
            }
            var val = this.newUuid();
            $(this).data("value", val);
            return val;
        }
    },
    number:{
        strip:function(num, precision) {
            var precision = precision || 12;
            return +parseFloat(num.toPrecision(precision));
        },
        digitLength:function(num) {
            // Get digit length of e
            var eSplit = num.toString().split(/[eE]/);
            var len = (eSplit[0].split('.')[1] || '').length - (+(eSplit[1] || 0));
            return len > 0 ? len : 0;
        },
        times:function(num1, num2) {
            var num1Changed = Number(num1.toString().replace('.', ''));
            var num2Changed = Number(num2.toString().replace('.', ''));
            var baseNum = this.digitLength(num1) + this.digitLength(num2);
            return num1Changed * num2Changed / Math.pow(10, baseNum);
        },
        plus:function(num1, num2) {
            var baseNum = Math.pow(10, Math.max(this.digitLength(num1), this.digitLength(num2)));
            return (this.times(num1, baseNum) + this.times(num2, baseNum)) / baseNum;
        },
        minus:function(num1, num2) {
            var baseNum = Math.pow(10, Math.max(this.digitLength(num1), this.digitLength(num2)));
            return (num1 * baseNum - num2 * baseNum) / baseNum;
        },
        divide:function(num1, num2) {
            var num1Changed = Number(num1.toString().replace('.', ''));
            var num2Changed = Number(num2.toString().replace('.', ''));
            return this.times((num1Changed / num2Changed), Math.pow(10, this.digitLength(num2) - this.digitLength(num1)));
        },
        round:function(num, ratio) {
            var ratio = ratio || 2;
            var base = Math.pow(10, ratio);
            return this.divide(Math.round(this.times(num, base)), base);
        }
    },
    /**
     * 通过汇率计算
     * @param currency 对象 {sourceMoney：待计算货币金额,fromCurrencyCode: 待转换货币的货币代码，toCurrencyCode:转换到货币的货币代码}
     * @param exchangeRate 汇率对象 { exchangeRate  fixExchangeRate  fromExchangeUnit  toExchangeUnit }
     * @param reverse 是否逆向转换
     * @returns 转换后金额
     */
    calcMoney: function (currency, exchangeRate, reverse) {
        if(!currency.sourceMoney){
            return 0;
        }
        if (currency.fromCurrencyCode == currency.toCurrencyCode) {
            return currency.sourceMoney;
        }
        if (!exchangeRate.toExchangeUnit || !exchangeRate.exchangeRate || !exchangeRate.fromExchangeUnit) {
            return currency.sourceMoney;
        }
        var destMoney;
        if(reverse){
            //逆向转换 money /toExchangeUnit /exchangeRate * fromExchangeUnit
            destMoney = this.number.divide(this.number.divide(currency.sourceMoney, exchangeRate.toExchangeUnit),exchangeRate.exchangeRate);
            destMoney = this.number.times(destMoney, exchangeRate.fromExchangeUnit);
        }else{
            //正向转换 money * toExchangeUnit * exchangeRate / fromExchangeUnit
            destMoney = this.number.times(this.number.times(currency.sourceMoney, exchangeRate.toExchangeUnit),exchangeRate.exchangeRate);
            destMoney = this.number.divide(destMoney, exchangeRate.fromExchangeUnit);
        }
        return this.number.round(destMoney);
    },
    message: function (msg) {
        EUI.ProcessStatus({
            sucess:false,
            //hintText: "温馨提示",
            title: this.lang.hintText,
            msg: msg,
        });
    },
    /**
     *  获取字符串、数组或对象的hash值
     * @param param 参数：字符串或对象
     * @returns {number} hash值
     */
    hashCode: function (param){
        var str;
        if((typeof param=='string') && (param.constructor==String)){
            str = param;
        }else if((typeof param=='object') && (param.constructor==Object)){
            str = JSON.stringify(param);
        }else if((typeof param=='object') && (param.constructor==Array)){
            str = JSON.stringify(param);
        }else{
            //paramErrorText:"参数不是字符串或者对象类型!",
            throw new Error(this.lang.paramErrorText);
        }
        var hash = 5381;
        for (var i = 0,len=str.length; i < len; i++) {
            char = str.charCodeAt(i);
            hash = ((hash << 5) + hash) + char;    /* hash * 33 + c */
        }
        return hash;
    }
};

/*
 * 移动端模拟导航可点击自动滑动
 * 导航可左右滑动，可点击边缘的一个，自动滚动下一个到可视范围【依赖于iscroll.js】
 */
(function ($) {
    $.fn.navbarscroll = function (options) {
        //各种属性、参数
        var _defaults = {
            className:'active', //当前选中点击元素的class类名
            clickScrollTime:300, //点击后滑动时间
            duibiScreenWidth:0.4, //单位以rem为准，默认为0.4rem
            scrollerWidth:3, //单位以px为准，默认为3,[仅用于特殊情况：外层宽度因为小数点造成的不精准情况]
            defaultSelect:0, //初始选中第n个，默认第0个
            fingerClick:0, //目标第0或1个选项触发,必须每一项长度一致，方可用此项
            endClickScroll:function(thisObj){}//回调函数
        }
        var _opt = $.extend(_defaults, options);
        this.each(function () {
            //插件实现代码
            var _wrapper = $(this);

            var _obj_scroller = _wrapper.children('.scroller');
            var _obj_ul = _obj_scroller.children('ul');
            var _obj_li = _obj_ul.children('li');
            var _scroller_w = 0;
            _obj_li.css({"margin-left":"0","margin-right":"0"});
            for (var i = 0; i < _obj_li.length; i++) {
                _scroller_w += _obj_li[i].offsetWidth;
            }
            _obj_scroller.width(_scroller_w+_opt.scrollerWidth);
            var myScroll = new IScroll('#'+_wrapper.attr('id'), {
                eventPassthrough: true,
                scrollX: true,
                scrollY: false,
                preventDefault: false
            });
            _init(_obj_li.eq(_opt.defaultSelect));
            _obj_li.click(function(){
                _init($(this));
            });
            //解决PC端谷歌浏览器模拟的手机屏幕出现莫名的卡顿现象，滑动时禁止默认事件
            // _wrapper[0].addEventListener('touchmove',function (e){e.preventDefault();},false);
            function _init(thiObj){
                var $this_obj=thiObj;
                var _win = $(window);
                var _win_width = _win.width(),
                    _wrapper_width = _wrapper.width(),
                    _wrapper_off_left = _wrapper.offset().left;

                var _wrapper_off_right = _win_width-_wrapper_off_left-_wrapper_width;//
                var duibi=_opt.duibiScreenWidth*_win_width/10,
                    this_index=$this_obj.index(),
                    this_off_left=$this_obj.offset().left,
                    this_pos_left=$this_obj.position().left,
                    this_width=$this_obj.width(),
                    this_prev_width=$this_obj.prev('li').width(),
                    this_next_width=$this_obj.next('li').width();
                // debugger
                var this_off_right=_win_width-this_off_left-this_width;
                if(_scroller_w+2>_wrapper_width){
                    if(_opt.fingerClick==1){
                        if(this_index==1){
                            myScroll.scrollTo(-this_pos_left+this_prev_width,0, _opt.clickScrollTime);
                        }else if(this_index==0){
                            myScroll.scrollTo(-this_pos_left,0, _opt.clickScrollTime);
                        }else if(this_index==_obj_li.length-2){
                            myScroll.scrollBy(this_off_right-_wrapper_off_right-this_width,0, _opt.clickScrollTime);
                        }else if(this_index==_obj_li.length-1){
                            myScroll.scrollBy(this_off_right-_wrapper_off_right,0, _opt.clickScrollTime);
                        }else{
                            if(this_off_left-_wrapper_off_left-(this_width*_opt.fingerClick)<duibi){
                                myScroll.scrollTo(-this_pos_left+this_prev_width+(this_width*_opt.fingerClick),0, _opt.clickScrollTime);
                            }else if(this_off_right-_wrapper_off_right-(this_width*_opt.fingerClick)<duibi){
                                myScroll.scrollBy(this_off_right-this_next_width-_wrapper_off_right-(this_width*_opt.fingerClick),0, _opt.clickScrollTime);
                            }
                        }
                    }else{
                        if(this_index==1){
                            myScroll.scrollTo(-this_pos_left+this_prev_width,0, _opt.clickScrollTime);
                        }else if(this_index==_obj_li.length-1){
                            if(this_off_right-_wrapper_off_right>1||this_off_right-_wrapper_off_right<-1){
                                myScroll.scrollBy(this_off_right-_wrapper_off_right,0, _opt.clickScrollTime);
                            }
                        }else{
                            if(this_off_left-_wrapper_off_left<duibi){
                                myScroll.scrollTo(-this_pos_left+this_prev_width,0, _opt.clickScrollTime);
                            }else if(this_off_right-_wrapper_off_right<duibi){
                                myScroll.scrollBy(this_off_right-this_next_width-_wrapper_off_right,0, _opt.clickScrollTime);
                            }
                        }
                    }
                }
                $this_obj.addClass(_opt.className).siblings('li').removeClass(_opt.className);
                _opt.endClickScroll.call(this,$this_obj);
            }
        });
    };
})(jQuery);